pdf加密解密

参考链接:https://blog.csdn.net/aaahtml/article/details/116836899
参考链接:https://blog.csdn.net/weixin_42350212/article/details/117031929

# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PyPDF2

import PyPDF2
import itertools
# 加密PDF
def encrypt(old_Path, new_Path):
    """
    :param old_Path: 待加密文件的路径名
    :param new_Path: 加密之后的文件路径名
    """
    with open(old_Path, 'rb') as pdfFile:
        pdfReader = PyPDF2.PdfFileReader(pdfFile)
        # 创建pdfWriter对象用于写出PDF文件
        pdfWriter = PyPDF2.PdfFileWriter()
        # pdf对象加入到pdfWriter对象中
        for pageNum in range(pdfReader.numPages):
            pdfWriter.addPage(pdfReader.getPage(pageNum))
        # 密码设置为5243
        pdfWriter.encrypt('5243')
        with open(new_Path, 'wb') as resultPDF:
            pdfWriter.write(resultPDF)
            print('加密成功!')

# 数字解密
def decrypt(old_Path, new_Path):
    """
    :param old_Path: 待加密文件的路径名
    :param new_Path: 加密之后的文件路径名
    """
    with open(old_Path, 'rb') as pdfFile:
        pdfReader = PyPDF2.PdfFileReader(pdfFile)
        pdfWriter = PyPDF2.PdfFileWriter()
        # 判断文件是否加密
        if pdfReader.isEncrypted:
            # 判断密码是否正确
            for i in range(10000):
                # 生成四位数密码
                pwd = str(i).zfill(4)
                if pdfReader.decrypt(pwd):
                    for pageNum in range(pdfReader.numPages):
                        pdfWriter.addPage(pdfReader.getPage(pageNum))
                    with open(new_Path, 'wb') as resultFile:
                        pdfWriter.write(resultFile)
                        print('成功了!密码是:'+pwd)
            else:
                print('密码错了!哼~~~')
        else:
            print('没有加密呀~~~')

# 密码本解密
def decryptBypass(password_Path, pdf_Path):
    passw = []
    file = open(password_Path)
    for line in file.readlines():
        passw.append(line.strip())
    file.close()

    pdf_reader = PyPDF2.PdfFileReader(pdf_Path)
    for i in passw:
        if pdf_reader.decrypt(i):
            print(f'破解成功,密码为{i}')
        else:
            print(f'破解不成功,密码{i}错误')



# 无密码本,穷举解密
def decryptByexhaustive(pdf_Path):
    mylist = ("".join(x) for x in itertools.product("12345a", repeat=5))
    pdf_reader = PyPDF2.PdfFileReader(pdf_Path)
    while True:
        i = next(mylist)
        if pdf_reader.decrypt(i):
            print(f'破解成功,密码为{i}')
            break
        else:
            print(f'破解不成功,密码{i}错误')

if __name__ == '__main__':
    # encrypt("../pdfadad.pdf", "pdfadad3.pdf")
    # decryptBypass("password.txt", "pdfadad3.pdf")
    decryptByexhaustive("pdfadad3.pdf")
    # decrypt("pdfadad3.pdf", "pdfadad4.pdf")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值